package com.ruoyi.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.PrimaryKeyUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.oms.entity.Order;
import com.ruoyi.oms.entity.OrderItem;
import com.ruoyi.oms.entity.OrderRecod;
import com.ruoyi.oms.mapper.OrderMapper;
import com.ruoyi.oms.service.IOrderItemService;
import com.ruoyi.oms.service.IOrderRecodService;
import com.ruoyi.oms.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.ums.entity.MemberAddress;
import com.ruoyi.ums.service.IMemberAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author kenny
 * @since 2021-11-02
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private IOrderRecodService orderRecodService;

    public ApiResult<String> createOrder(Order order, List<OrderItem> items) {
        if (order.getMemberAddressId() != null) {
            MemberAddress address = new MemberAddress();
            BeanUtils.copyBeanProp(address, order);
            memberAddressService.insertAddress(address);
        }
        String no = PrimaryKeyUtils.generateCode("", null);
        order.setOrderSn(no);
        this.baseMapper.insert(order);

        for (OrderItem item : items) {
            item.setOrderId(order.getId());
        }
        orderItemService.saveBatch(items);

        OrderRecod record = new OrderRecod();
        record.setOrderId(order.getId());
        record.setOperation(order.getMemberId().toString());
        record.setCreateTime(LocalDateTime.now());
        orderRecodService.save(record);
        return ApiResult.success(no);
    }


    public Page<Order> selectListByMemberId(Integer pageNum, Integer pageSize,Long memberId) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Order::getMemberId,memberId);
        Page<Order> orderPage = baseMapper.selectPage(page, wrapper);
        return orderPage;
    }
}
